@tool
class_name EntityData
extends Resource

@export var ID:String
@export var attribute_set:AttributeSet
@export_group("LayerMask")
@export_flags_2d_physics var obstacle_layer_mask:int:
	get:
		return obstacle_layer_mask
	set(value):
		obstacle_layer_mask = value
		data_changed.emit("attribute","obstacle_layer_mask")
@export_group("")

#region 信号
# data变化
# tag_space:一级分类
# tag:二级分类
signal data_changed(tag_space:String,tag:String,old_value,new_value)
#endregion
#region 运行时属性
var entity:Entity
var connect_obj_dict:Dictionary = {}
var inited:bool = false
#endregion
#region 公共方法
## 初始化运行时属性
func init(entity:Entity):
	if inited:
		return
	inited = true
	## 初始化属性
	self.entity = entity
	connect_obj_dict = {}
	attribute_set.init({"Entity" = entity})
	for attribute in attribute_set.attributes:
		connect_obj_dict[attribute.attribute_changed] = ConnectObj.new(attribute.attribute_changed,[_on_attribute_changed])
		
	## 连接信号
	connect_signal()
## 销毁时调用
func destroy():
	disconnect_signal()
func connect_signal():
	connect_obj_dict["data_changed"] = ConnectObj.new(data_changed,[_on_data_changed])
func disconnect_signal():
	for connect_obj:ConnectObj in connect_obj_dict.values():
		if connect_obj:
			connect_obj.disconnect_all()
func get_cost(cost_attribute:String,init_val:float = 0):
	var attribute_name = cost_attribute
	var attribute:Attribute = find_attribute(attribute_name)
	return get_attribute_value(attribute_name)
func set_cost(cost_attribute:String,cost_value,init_val:float = 0):
	var cur_cost:float = get_cost(cost_attribute,init_val)
	if cur_cost == null:
		return
	var old_value = cur_cost
	cur_cost += cost_value
	var attribute_name = cost_attribute
	var attribute:Attribute = find_attribute(attribute_name)
	attribute.force_set_base_value(cur_cost)
	data_changed.emit("attribute",cost_attribute,old_value,cur_cost)
func find_attribute(attribute_name:String) -> Attribute:
	return attribute_set.find_attribute(attribute_name)
func get_attribute_value(attribute_name:String,default_value = null):
	var attribute:Attribute = find_attribute(attribute_name)
	if attribute:
		return attribute.get_value()
	return default_value
func add_attribute_value(attribute_name:String,property_type:CompositeProperty.PropertyType,init_value):
	var attribute = attribute_set.add_attribute(attribute_name,property_type,init_value)
	if attribute:
		connect_obj_dict[attribute.attribute_changed] = ConnectObj.new(attribute.attribute_changed,[_on_attribute_changed])
#endregion
#region 私有方法
func _on_attribute_changed(attribute:Attribute,old_value,new_value):
	data_changed.emit("attribute",attribute.attribute_name,old_value,new_value)
func _on_data_changed(tag_space:String,tag:String,old_value,new_value):
	pass
#endregion
#region 生命周期函数
func _init() -> void:
	if Engine.is_editor_hint():
		resource_local_to_scene = true
#endregion
